package com.asiainfo.kbisheet.components.grid
{
	import com.asiainfo.kbisheet.common.Util;
	import com.asiainfo.kbisheet.components.condition.ConditionInput;
	import com.asiainfo.kbisheet.components.condition.ConditionItem;
	import com.asiainfo.kbisheet.control.MessageControl;
	import com.asiainfo.kbisheet.model.KbsModel;
	import com.asiainfo.kbisheet.model.SettingModel;
	import com.asiainfo.kbisheet.vo.SettingVO;
	
	import flash.events.ContextMenuEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	
	import mx.controls.AdvancedDataGrid;
	import mx.controls.Alert;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumnGroup;
	import mx.core.ClassFactory;
	import mx.events.AdvancedDataGridEvent;
	import mx.events.ListEvent;
	import mx.formatters.DateFormatter;
	
	import spark.components.Group;
	import spark.components.Scroller;
	import spark.components.SkinnableContainer;
	
	/**
	 * KBiSheet的高级表格容器
	 * 
	 */
	public class KbsAdg extends Group
	{
		private var sheetADG:AdvancedDataGrid;
		private var _dataXML:XML;
		private var dfconv:DateFormatter;
		private var nfInteger:KbsIntegerFormatter;
		private var nfCurrency:KbsCurrencyFormatter;
		private var pfPrecent:PrecentFormatter;
		private var miFrozen:ContextMenuItem;
		private var miUnfrozen:ContextMenuItem;
		private var miHidden:ContextMenuItem;
		private var columnIndex:int;
		[Bindable]
		private var kbsModel:KbsModel = KbsModel.getInstance();		
		
		protected var messageControl:MessageControl = new MessageControl();
		
		public function KbsAdg()
		{
			super();
		}
		
		public function set dataXML(value:XML):void{
			_dataXML = value;
			if(_dataXML != null && _dataXML.hasOwnProperty('row')){
				sheetADG.dataProvider = _dataXML.row;
			}
			else{
				sheetADG.dataProvider = null;
			}
		}
		
		public function set sortableColumns(value:Boolean):void{
			sheetADG.sortableColumns = value;
		}
		
		override public function set horizontalScrollPosition(value:Number):void{
			sheetADG.horizontalScrollPosition = value;
		}
		
		override public function set width(value:Number):void
		{
			super.width = value; 
			if(sheetADG){
				sheetADG.width = value;
			}
		}
		
		override protected function createChildren():void
		{
			super.createChildren();
			sheetADG = new AdvancedDataGrid();
			sheetADG.percentWidth=100; 
			sheetADG.percentHeight=100;
			sheetADG.horizontalScrollPolicy="auto" ;
			sheetADG.addEventListener(ListEvent.ITEM_CLICK, onItemClick);
			sheetADG.addEventListener(AdvancedDataGridEvent.HEADER_RELEASE,advancedDataGridSort);
			addElement(sheetADG);
			
			dfconv = new DateFormatter();
			dfconv.formatString = "YYYY/MM/DD";
			
			nfInteger = new KbsIntegerFormatter();
			nfCurrency = new KbsCurrencyFormatter();
			pfPrecent = new PrecentFormatter();
			initContextMenu();
		}
		
		private function initContextMenu():void
		{
			kbsModel.addEventListener("updateHiddenColumnUUIDs",hosColumns);
			miFrozen = new ContextMenuItem('冻结当前列',false);
			miUnfrozen = new ContextMenuItem('解除冻结',false);
			
			
			var myMenu:ContextMenu = new ContextMenu();
			myMenu.customItems.push(miFrozen);
			myMenu.customItems.push(miUnfrozen);
			
			miFrozen.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,menuItemHandler);
			miUnfrozen.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,menuItemHandler);
			
			myMenu.hideBuiltInItems();
			sheetADG.contextMenu = myMenu;
		}
		
		private function menuItemHandler(event:ContextMenuEvent):void
		{
			switch (event.target)
			{
				case miFrozen:
					fixCellHandler('frozen');
					break;
				
				case miUnfrozen:
					fixCellHandler('unfrozen');
					break;
			}
		}
		
		private function fixCellHandler(cmd:String):void
		{
			switch (cmd)
			{
				case "frozen":
					sheetADG.lockedColumnCount = columnIndex + 1;
					break;
				case "unfrozen":
					sheetADG.lockedColumnCount = 0
					break;
			}
		}
		
		/**显示或隐藏列*/
		public function hosColumns(event:Event = null):void{
			updateMessage("KbsAdg:hosColumns():处理显示/隐藏列...");
			var groupedColumns : Array   = new Array();
			var lockedColumnCount:int = 0;
			var lockedColumnFind:Boolean = false;
			for each(var column:XML in kbsModel.columnsXML.column){
				var advancedDataGridColumn:AdvancedDataGridColumn = createColumn(column);
				if(advancedDataGridColumn){
					groupedColumns.push(advancedDataGridColumn);
					if(!lockedColumnFind){
						lockedColumnCount++;
					}
				}
				if(column.hasOwnProperty('@locked') && column.@locked.toString() =='true'){
					lockedColumnFind = true;
				}
			}
			if(!lockedColumnFind){
				lockedColumnCount = 0;
			}
			sheetADG.groupedColumns = groupedColumns;
			kbsModel.groupedColumns = groupedColumns;
			sheetADG.lockedColumnCount = lockedColumnCount;
		}			
		
		
		/*创建列*/
		private function createColumn(columnXML:XML, parentHeaderRender:ClassFactory = null):AdvancedDataGridColumn{
			var settingVO:SettingVO = SettingModel.getInstance().settingVO;
			
			if(columnXML.hasOwnProperty('@uuid')){
				var uuid:String = columnXML.@uuid;
				if(kbsModel.hiddenColumnUUIDs.contains(uuid)){
					return null;
				}
			}				
			
			var visible:Boolean = !(columnXML.hasOwnProperty('@hidden') && columnXML.@hidden == "true");
			if(columnXML.hasOwnProperty("visible")){
				var visibleXML:XML = XML(columnXML.visible);						
				visible = 
					(visibleXML.hasOwnProperty('@dependence') && kbsModel.getConditionItemById(visibleXML.@dependence) == columnXML.@name) 
					|| (visibleXML.children().length() > 0 && kbsModel.isIfsTrue(visibleXML.children()));
			}
			
			
			if(visible){
				var title:String = columnXML.@title;
				
				/*是否使用自定义的列头*/
				var kbsAdgHeaderRender:ClassFactory;
				if(columnXML.hasOwnProperty("@bgcolor")){
					var bgcolor:uint = uint(columnXML.@bgcolor);
					kbsAdgHeaderRender = new ClassFactory(KbsAdgHeaderRenderer);
					kbsAdgHeaderRender.properties = {bgcolor:bgcolor}; 
				}
				
				/*继承于父列*/
				if(kbsAdgHeaderRender == null && parentHeaderRender != null){
					kbsAdgHeaderRender = parentHeaderRender;
				}
				
				
				/*创建列头*/
				if(columnXML.hasOwnProperty("column")){
					/*非最底层列*/
					var adgcg : AdvancedDataGridColumnGroup = new AdvancedDataGridColumnGroup();
					adgcg.headerText = title;
					adgcg.headerWordWrap = true;
					adgcg.minWidth = 100;
					if(kbsAdgHeaderRender != null){
						adgcg.headerRenderer = kbsAdgHeaderRender;
					}
					for each(var column:XML in columnXML.column){
						var advancedDataGridColumn:AdvancedDataGridColumn = createColumn(column, kbsAdgHeaderRender);
						if(advancedDataGridColumn){
							adgcg.children.push(advancedDataGridColumn);
						}
					}	
					return adgcg;
				}
				else{
					/*最底层列*/
					var adgc : AdvancedDataGridColumn = new AdvancedDataGridColumn();
					adgc.headerText = title;
					adgc.headerWordWrap = true;
					adgc.dataField=columnXML.@name;
					if(kbsAdgHeaderRender != null){
						/*列颜色*/
						adgc.headerRenderer = kbsAdgHeaderRender;
						adgc.setStyle("backgroundColor",kbsAdgHeaderRender.properties.bgcolor);
					}					
					
					var isNumber:Boolean = columnXML.hasOwnProperty('@type') && settingVO.numbers.contains(columnXML.@type.toString().toUpperCase());
					
					if(isNumber){
						adgc.setStyle("textAlign", "right");
						adgc.formatter = nfCurrency;
					}
					
					if(columnXML.hasOwnProperty('@format')){
						if(columnXML.@format == "int"){
							adgc.formatter = nfInteger;
						}
						else if(columnXML.@format == "percent"){
							adgc.formatter = pfPrecent;
						}
						else if(columnXML.@format == "null" || columnXML.@format == ""){
							adgc.formatter = null;
						}
					}
					
					if(columnXML.hasOwnProperty('link')){
						var ifactory :ClassFactory = new  ClassFactory(RenderLink);
						ifactory.properties = {columnName:columnXML.@name, formatter:adgc.formatter, textAlign:adgc.getStyle("textAlign"), kbsAdg:this};
						adgc.itemRenderer = ifactory;
					}
					adgc.minWidth=100;
					
					/*宽度计算*/
					if(columnXML.hasOwnProperty('@width')){
						var width:String = columnXML.@width;
						try{
							adgc.width = Number(width);
						}
						catch(error:Error){
							adgc.width = 100;
						}
					}
					return adgc;						
				}
			}
			else{
				return null;
			}
		}
		
		
		/**
		 * 点击AdvancedDataGrid列头上的排序按钮
		 */
		private function advancedDataGridSort(evt:AdvancedDataGridEvent):void {				
			var column:AdvancedDataGridColumn = AdvancedDataGridColumn(evt.currentTarget.columns[evt.columnIndex]);
			if(column != null){
				kbsModel.horizontalScrollPosition = sheetADG.horizontalScrollPosition;					
				kbsModel.remoteOrderByDirection = (kbsModel.remoteOrderByDirection != 'asc')?'asc':'desc';
				kbsModel.order = column.dataField + ' ' + kbsModel.remoteOrderByDirection;
				kbsModel.queryVO.order = kbsModel.order;
				this.parentDocument.doPaginate();
			}
		}			
		
		/** 导出Excel */
		public function getExportXMLString():String{
			var excelXML:XML = <excel/>;
			excelXML.@title = "导出数据";
			var headerXML:XML = getExcelHeaderXML(sheetADG.groupedColumns);					
			excelXML.appendChild(headerXML);
			excelXML.appendChild(_dataXML);
			return excelXML.toXMLString();			
		}
		
		private function getExcelHeaderXML(groupedColumns:Array):XML{
			var headerXML:XML = <header/>;
			for each(var column:AdvancedDataGridColumn in groupedColumns){
				headerXML.appendChild(getExcelHeaderColumnXML(column));
			}
			
			var allHeight:int = getChildrenLevel(XMLList(headerXML));
			headerXML.@height = allHeight;
			setHW(headerXML.column, allHeight, 0);
			return headerXML;
		}
		
		private function getExcelHeaderColumnXML(column:AdvancedDataGridColumn):XML{
			var columnXML:XML = <column/>;	
			columnXML.@title = column.headerText;			
			if (column is AdvancedDataGridColumnGroup){
				for each(var child:AdvancedDataGridColumn in (AdvancedDataGridColumnGroup(column)).children){
					columnXML.appendChild(getExcelHeaderColumnXML(child));
				}
			}
			else{
				columnXML.@name = column.dataField;
				
				var textAlign:String = column.getStyle("textAlign");
				
				if(textAlign == "right"){
					if(column.formatter != null){
						if(column.formatter == pfPrecent){
							columnXML.@format = "percent";
						}
						else if(column.formatter == nfInteger){
							columnXML.@format = "int";
						}
						else if(column.formatter == nfCurrency){
							columnXML.@format = "currency";
						}
					}
				}
			}
			return columnXML;
		}
		
		private  function setHW(columnXMLList:XMLList, allHeight:int, lineNumber:int):void{
			for each(var columnXML:XML in columnXMLList){
				if(lineNumber < allHeight){
					var width:int = getLowestSize(columnXML);
					if(width == 0){
						width = 1;
					}
					columnXML.@width = width;						
					
					if(!columnXML.hasOwnProperty('column')){
						columnXML.@height = allHeight - lineNumber;
					}
					else{
						columnXML.@height = 1;
						setHW(columnXML.column, allHeight, lineNumber+1);
					}
				} 
			}
		}
		
		/*最底层子节点数量*/
		private  function getLowestSize(node:XML):int{
			return  node..column.(!hasOwnProperty('column') && hasOwnProperty('@name') && @name != '').length();
		}
		
		/*得到一个节点的深度*/
		private  function getChildrenLevel(node:XMLList):int{	
			var level:int = 0;
			while(!isLowest(node)){
				node = node.column;
				level++;
			}
			return level;
		}
		
		/*判断是否达到最低层*/
		private  function isLowest(node:XMLList):Boolean{
			return !node.hasOwnProperty('column');
		}
		
		/*下钻的处理*/
		public function linkHandler(selectedColumnName:String, item:XML):void
		{				
			/*取选中表格的原始XML定义*/
			var selectedColumnXML:XML = kbsModel.columnsXML..column.(hasOwnProperty('@name') && @name == selectedColumnName)[0];
			
			var isInline:String = selectedColumnXML.link.@inline;
			if(isInline == "true"){
				
			}
			else{
				linkURL(item,selectedColumnXML);
			}				
		}
		
		/*内链接的处理*/
		private function linkInline(item:XML,selectedColumnXML:XML):void{
			for each(var parameterXML:XML in selectedColumnXML.link.parameters.parameter){
				var parameterKey:String = parameterXML.@key;
				var conditionItem : ConditionItem = kbsModel.getConditionItemByColumn(parameterKey);
				if(conditionItem != null){
					conditionItem.preset = getColumnValue(item, parameterKey);
				}
			}
		}
		
		/*外链接的处理*/
		private function linkURL(item:XML,selectedColumnXML:XML):void
		{	
			if(selectedColumnXML.hasOwnProperty('link')){
				var linkXML:XML = XML(selectedColumnXML.link);
				/*引用的公共连接配置*/
				var reference:String = linkXML.@reference;
				var url:String = null;
				var linkString:String = "?";
				if(Util.isNotNull(reference)){
					var commonLinkXML:XML = kbsModel.getLink(reference);
					//trace(commonLinkXML.toXMLString());
					url = commonLinkXML.@url;
					for each(var commonParameterXML:XML in commonLinkXML.parameters.parameter){
						url = extendURL(item,selectedColumnXML,commonParameterXML,url,linkString, true);
						linkString = "&";
					}
				}
				else{					
					url = linkXML.@url;					
				}				
				
				for each(var parameterXML:XML in linkXML.parameters.parameter.(!hasOwnProperty('@parent'))){
					url = extendURL(item,selectedColumnXML,parameterXML,url,linkString, false);
					linkString = "&";
				}
				updateMessage("KbsAdg:linkURL():最终URL:" + url);
				navigateToURL(new URLRequest(url));
			}
		}
		
		
		
		/*连接URL*/
		private function extendURL(item:XML, selectedColumnXML:XML, parameterXML:XML, url:String, linkString:String, common:Boolean):String
		{	
			/*<parameter key="descKey" value="snap_cmcc_cnts" />*/
			/*<parameter key="descKey" value="{column@name}" />*/
			/*<parameter key="county_id" />*/
			/*<parameter key="page" value="http://10.168.3.202/kpi2005/KPI_Popedom/Report/201005/st_51117_dm_detail.aspx" question="$" and="%">*/
			/*	<parameter key="user_id" />*/
			/*</parameter>*/
			var parameterKey:String = parameterXML.@key;
			
			/*排除未设置@key的配置*/
			if(Util.isNotNull(parameterKey)){
				var parameter:String = parameterKey + "=";
				var parameterValue:String = null;
				
				if(!parameterXML.hasOwnProperty('@value')){
					if(parameterXML.hasOwnProperty('@conditionId')){
						/*直接取条件框的值*/						
						parameterValue = kbsModel.getConditionItemValueById(parameterXML.@conditionId);
						updateMessage("KbsAdg:extendURL():直接取条件框的值:" + parameterXML.@conditionId + "=" + parameterValue);
					}
					else{
						var parameterColumn:String = parameterXML.@column;
						/*如果没有设@column，则以@key为其值*/
						if(Util.isNull(parameterColumn)){
							parameterColumn = parameterKey;
						}
						
						/*得到列值*/
						parameterValue = getColumnValue(item, parameterColumn);
					}
				}
				else{
					parameterValue = parameterXML.@value;
					if(parameterValue == '{column@name}'){
						parameterValue = selectedColumnXML.@name;
					}
				}
				
				if(parameterXML.hasOwnProperty('parameter')){
					var question:String = parameterXML.hasOwnProperty('@question') ? parameterXML.@question : "?";
					var and:String = parameterXML.hasOwnProperty('@and') ? parameterXML.@and : "&";
					parameterValue = extendSubURL(item, selectedColumnXML, parameterXML.parameter, parameterValue, parameterKey, question,and,common);
				}
				parameter = parameter + parameterValue;
				updateMessage("KbsAdg:extendURL():URL参数:" + parameter);
				url = url + linkString + parameter;
			}
			return url;
		}	
		
		/*递归链接的处理*/
		private function extendSubURL(item:XML, selectedColumnXML:XML, parameterXMLList:XMLList, url:String, parent:String, question:String,and:String,common:Boolean):String
		{				
			var linkString:String = question;
			
			for each(var parameterXML:XML in parameterXMLList){
				url = extendURL(item,selectedColumnXML,parameterXML,url,linkString, true);
				linkString = and;
			}
			
			
			if(common){
				for each(var selectedParameterXML:XML in selectedColumnXML.link.parameters.parameter.(hasOwnProperty('@parent'))){
					if(selectedParameterXML.@parent == parent){
						url = extendURL(item,selectedColumnXML,selectedParameterXML,url,linkString, false);
						linkString = and;
					}
				}
			}
			return url;
		}
		
		private function getColumnValue(item:XML,column:String ):String
		{	
			/*得到列值*/
			var value : String = item[column].toString();
			
			return value;
		}
		
		
		
		private function onItemClick(event:ListEvent):void{
			columnIndex = event.columnIndex;
		}
		
		protected function updateMessage(message:String):void{
			messageControl.updateMessage(message);
		}
	}
}